package org.mozhu.mboot.admin.system.auth.service;

import org.apache.commons.lang3.ArrayUtils;
import org.mozhu.mboot.admin.system.auth.entity.GroupAuth;
import org.mozhu.mboot.admin.system.auth.repository.GroupAuthRepository;
import org.mozhu.mboot.admin.system.group.entity.Group;
import org.mozhu.mboot.admin.system.group.service.GroupService;
import org.mozhu.mboot.core.data.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Transactional
@Service("groupAuthService")
public class GroupAuthServiceImpl extends BaseService<GroupAuth, Long> implements GroupAuthService {

    @Autowired
    GroupService groupService;

    protected GroupAuthRepository getBaseRepository() {
        return (GroupAuthRepository) baseRepository;
    }

    @Override
    public GroupAuth findByGroupId(Long groupId) {
        return getBaseRepository().findByGroupId(groupId);
    }

    @Override
    public void addGroupAuth(Long[] groupIds, GroupAuth m) {
        if (m == null) {
            return;
        }
        if (m.getId() != null) {
            // update
            save(m);
            return;
        }
        // add and merge
        if (ArrayUtils.isNotEmpty(groupIds)) {
            for (Long groupId : groupIds) {
                Group group = groupService.findById(groupId);
                if (group == null) {
                    continue;
                }
                GroupAuth auth = this.getBaseRepository().findByGroupId(groupId);
                if (auth == null) {
                    auth = new GroupAuth();
                    auth.setGroupId(groupId);
                }
                auth.addRoleIds(m.getRoleIds());
                auth.addPermissionIds(m.getPermissionIds());
                save(auth);
            }
        }

    }

}
